from flask import Blueprint, jsonify, render_template, request
from marshmallow import INCLUDE

from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils import validate
from applications.common.utils.http import success_api, fail_api, table_api
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Title, Position, Dept, PositionDepartment
from applications.schemas import TitleOutSchema, TitleInSchema, PositionOutSchema, DeptOutSchema, PositionInSchema

position_bp = Blueprint('position', __name__, url_prefix='/admin/position')


@position_bp.get('/')
def main():
    return render_template('admin/position/main.html')


@position_bp.get('/data')
def data():
    # 获取请求参数
    positionName = xss_escape(request.args.get('positionName', type=str))

    # 查询参数构造
    mf = ModelFilter()
    if positionName:
        mf.contains(field_name="position_name", value=positionName)
    # orm查询
    # 使用分页获取data需要.items
    positions = Position.query.filter(mf.get_filter(model=Position)).layui_paginate()
    count = positions.total
    data = model_to_dicts(schema=PositionOutSchema, data=positions.items)
    return table_api(data=data, count=count)


@position_bp.get('/add')
def add():
    return render_template('admin/position/add.html')


@position_bp.get('/deptList')
def getDeptList():
    dept = Dept.query.all()
    power_data = curd.model_to_dicts(schema=DeptOutSchema, data=dept)
    for data in power_data:
        data['checkArr'] = '0'
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": power_data
    }
    print(res)
    return jsonify(res)


@position_bp.post('/save')
def save():
    req = request.json
    validate.check_data(PositionInSchema(unknown=INCLUDE), req)

    dept_str = req['deptId']
    position_name = req['positionName']
    if position_name == '':
        return fail_api(msg="职位名称不能为空")
    remark = req['remark']
    status = req['status']
    dept_ids = dept_str.split(',')
    position = Position(position_name=position_name, remark=remark, status=status)
    db.session.add(position)
    db.session.commit()
    try:
        for id in dept_ids:
            if id != '':
                position_department = PositionDepartment(position_id=position.id, department_id=id)
                db.session.add(position_department)
            else:
                print(dept_ids)
    except:
        return fail_api("数据格式错误")

    db.session.commit()
    return success_api(msg="成功")


@position_bp.get('/edit')
def edit():
    _id = request.args.get("positionId")
    position = curd.get_one_by_id(model=Position, id=_id)
    return render_template('admin/position/edit.html', position=position)


@position_bp.get('/deptList/<int:position_id>')
def getSelectedDepartment(position_id):
    select_dept = PositionDepartment.query.filter_by(position_id=position_id).all()
    dept = Dept.query.all()
    power_data = curd.model_to_dicts(schema=DeptOutSchema, data=dept)
    for data in power_data:
        data['checkArr'] = '0'
        for select in select_dept:
            if data['deptId'] == select.department_id:
                data['checkArr'] = '1'
                break
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": power_data
    }
    return jsonify(res)


# 启用
@position_bp.put('/enable')
def enable():
    id = request.json.get('positionId')
    if id:
        enable = 1
        d = Position.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="启用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


# 禁用
@position_bp.put('/disable')
def dis_enable():
    id = request.json.get('positionId')
    if id:
        enable = 0
        d = Position.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="禁用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


@position_bp.put('/update')
def update():
    json = request.json
    validate.check_data(PositionInSchema(unknown=INCLUDE), json)
    id = json.get("positionId"),
    data = {
        'position_name': validate.xss_escape(json.get("positionName")),
        'remark': validate.xss_escape(json.get("remark")),
        "status": validate.xss_escape(json.get("status"))
    }
    if data['position_name'] == '':
        return fail_api(msg="职位名称不能为空")
    d = Position.query.filter_by(id=id).update(data)
    if not d:
        return fail_api(msg="更新失败")

    dept_ids = json.get('deptId').split(',')

    # 原来存在的部门，如果现在不存在了，则删除该部门
    position_departments = PositionDepartment.query.filter_by(position_id=id).all()
    for position_department in position_departments:
        department_id = position_department.department_id
        if not str(department_id) in dept_ids:
            db.session.delete(position_department)
    # 如果字符串为空，则不需要新增
    if json.get('deptId') == '':
        db.session.commit()
        return success_api(msg="更新成功")

    # 现在存在的部门，如果原来不存在，则添加该部门
    for dept_id in dept_ids:
        exist = False
        for position_department in position_departments:
            if int(dept_id) == position_department.department_id:
                exist = True
                break
        if not exist:
            _position_department = PositionDepartment(position_id=id, department_id=int(dept_id))
            db.session.add(_position_department)
    db.session.commit()
    return success_api(msg="更新成功")


@position_bp.delete('/remove/<int:_id>')
def remove(_id):
    d = Position.query.filter_by(id=_id).delete()
    if not d:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")


@position_bp.delete('/batchRemove')
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        positions = Position.query.filter_by(id=id).first()
        res = Position.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="删除成功")


@position_bp.get('/department_position/<int:department_id>')
def getPositionByDepartmentId(department_id):
    position_info = []
    positionDepartments = PositionDepartment.query.filter_by(department_id=department_id).all()
    for positionDepartment in positionDepartments:
        position = Position.query.filter_by(id=positionDepartment.position_id).one_or_none()
        if position is not None and position.status == 1:
            position_info.append({'position_id': position.id,
                                  'position_name': position.position_name,
                                  'remark': position.remark})
    res = {
        'code': 0,
        'success': True,
        'msg': '查询成功',
        'data': {
            'position': position_info
        }
    }

    return res
